<template>
    <Dialog :title="comInfo.name" :show="true" @close="cancel" :width="415" height="auto" :left="10" :top="60">
        <div class="box">
            <!-- 功能按钮 -->
            <div class="cimrts-panel">
                <MainMenuList :menuList="cimrtsMenuList" @clickComponent="addComponent" :isDisabled="isDisabled" />
            </div>
            <!-- scenetree -->
            <div class="cimrts-scenetree" @click="whiteSpaceClick">
                <div class="tree-content">
                    <SceneTree :sceneTreeWrapper="cimrtsSceneTreeWrapper"></SceneTree>
                </div>
                <div class="submit">
                    <el-button @click.stop="deleteAllNode"> 删除所有节点</el-button>
                    <el-button @click.stop="submit" :disabled="isDisabled"> 提交</el-button>
                </div>
            </div>
            <!-- 基础信息 -->
            <div class="cimrts-info">
                <BaseInfo />
            </div>
        </div>
    </Dialog>
    <component v-for="item in menuListRef" :key="item.id" :is="item.com" :comInfo="item" @cancel="removeComponent">
    </component>

    <!-- 批量放置 编辑窗口 -->
    <BatchPlacePropPanel v-if="propSceneTree && propSceneTree.propType == 'batchSet'"
        :title="propSceneTree ? propSceneTree.sceneObject.name : '编辑面板'" :sceneObject="propSceneTree.sceneObject"
        @cancel="objm.propSceneTree = undefined"> </BatchPlacePropPanel>

    <!-- 水面修补 编辑窗口 -->
    <WaterMendPropPanel
        v-if="propSceneTree && propSceneTree.propType == 'waterMend' && propSceneTree.createOrEdit != 'property'"
        :title="propSceneTree ? propSceneTree.sceneObject.name : '编辑面板'" :sceneObject="propSceneTree.sceneObject"
        @cancel="objm.propSceneTree = undefined" :createOrEdit="propSceneTree.createOrEdit"> </WaterMendPropPanel>

    <!-- 水面修补 属性窗口 -->
    <WaterMendPropertyPanel
        v-if="propSceneTree && propSceneTree.propType == 'waterMend' && propSceneTree.createOrEdit == 'property'"
        :title="propSceneTree ? propSceneTree.sceneObject.name : '属性面板'" :sceneObject="propSceneTree.sceneObject"
        @cancel="objm.propSceneTree = undefined" :createOrEdit="propSceneTree.createOrEdit"> </WaterMendPropertyPanel>

    <!-- 要素编辑 编辑窗口 -->
    <FeatureEditPropPanel
        v-if="propSceneTree && propSceneTree.propType == 'featureEdit' && propSceneTree.createOrEdit == 'edit'"
        :title="propSceneTree ? propSceneTree.sceneObject.name : '编辑面板'" :sceneObject="propSceneTree.sceneObject"
        @cancel="objm.propSceneTree = undefined" :createOrEdit="propSceneTree.createOrEdit"> </FeatureEditPropPanel>

    <!-- 要素编辑 材质美化 -->
    <BeautifyMaterails
        v-if="propSceneTree && propSceneTree.propType == 'featureEdit' && propSceneTree.createOrEdit == 'beautifyMaterails'"
        :title="propSceneTree ? propSceneTree.sceneObject.name : '材质美化'" :sceneObject="propSceneTree.sceneObject"
        @cancel="objm.propSceneTree = undefined" :createOrEdit="propSceneTree.createOrEdit"> </BeautifyMaterails>

    <!-- 要素编辑 属性窗口 -->
    <FeatureEditPropertyPanel
        v-if="propSceneTree && propSceneTree.propType == 'featureEdit' && propSceneTree.createOrEdit == 'property'"
        :title="propSceneTree ? propSceneTree.sceneObject.name : '属性面板'" :sceneObject="propSceneTree.sceneObject"
        @cancel="objm.propSceneTree = undefined" :createOrEdit="propSceneTree.createOrEdit"> </FeatureEditPropertyPanel>

    <TooltipCom v-if="currentDialog == 'submit'" :content="'点击提交之后，会将所有正在编辑的对象提交到服务端处理，请稍等。'" :title="'提交'"
        :isVisible="true" @close="currentDialog = undefined" @confirm="submitConfirm" />

    <TooltipCom v-if="currentDialog == 'deleteAllNode'" :content="'点击删除所有节点之后，会将所有正在编辑的对象删除，请确认。'" :title="'删除所有节点'"
        :isVisible="true" @close="currentDialog = undefined" @confirm="deleteAllNodeConfirm" />

</template>
<script setup lang="ts">
import Dialog from "@/components/Dialog.vue";
import { MenuItem } from "@/scripts/dataTypes";
import { onMounted, ref, onBeforeUnmount, computed, watch, shallowRef } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import {
    createVueDisposer,
    toVR,
} from "earthsdk-ui";
import { cimrtsMenuList } from "@/scripts/menu/cimrts/cimrtsMenuList";
import SceneTree from "@/components/sceneTree/SceneTree.vue";
import { ElMessage } from "element-plus";
import { roundValues, roundValues2 } from "@/scripts/utils";
// @ts-ignore
import BaseInfo from "./BaseInfo.vue";
import MainMenuList from "@/components/common/MainMenuList.vue";
import { reqGetbpcByStore } from "@/api";
// import PropPanel from "@/components/propPanel/cimrts/index.vue";
import BatchPlacePropPanel from "@/components/propPanel/cimrts/BatchPlacePropPanel.vue";
import WaterMendPropPanel from "@/components/propPanel/cimrts/WaterMendPropPanel.vue";
import FeatureEditPropPanel from "@/components/propPanel/cimrts/FeatureEditPropPanel.vue";
import FeatureEditPropertyPanel from "@/components/propPanel/cimrts/FeatureEditPropertyPanel.vue";
import WaterMendPropertyPanel from "@/components/propPanel/cimrts/WaterMendPropertyPanel.vue";


import BeautifyMaterails from "@/components/propPanel/cimrts/BeautifyMaterails.vue";

import TooltipCom from "@/components/common/TooltipCom.vue";

const props = withDefaults(defineProps<{ comInfo: MenuItem }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    emits("cancel", props.comInfo.id);
};

const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();
const cimrtsSceneTreeWrapper = objm.cimrtsSceneTreeWrapper
const cimrtsManager = objm.cimrtsManager

const menuListRef = ref<any[]>([]);

const propSceneTree = toVR<any>(d, [objm, "propSceneTree"])

const tileServiceNameRef = toVR<any>(d, [cimrtsManager, "tileServiceName"]);


// 添加组件
const addComponent = async (item: any) => {
    if (item.id == "virtualLayer") {
        try {
            const res = await reqGetbpcByStore(tileServiceNameRef.value)
            // @ts-ignore
            if (res.status == "ok") {
                const layer = res.data.find((e: any) => e.name == "layer")
                const dataset = res.data.find((e: any) => e.name == "dataset")

                if ((!layer.value) || (!dataset.value)) {
                    ElMessage({
                        message: "切片不包含layer和dataset属性，无法查看图层",
                        type: "warning",
                    })
                    return;
                }
            }
        } catch (error) {
            console.error(error);
        }
    }
    if (item.id == "location") {
        cimrtsManager.eSRtsTileset.es3DTileset.flyTo();
        return;
    }
    if (item.id == "refresh") {
        cimrtsManager.eSRtsTileset.refresh();
        return;
    }
    if (item.id == "flyToFeature") {
        cimrtsManager.randomfeature()
        return;
    }
    item.status != "active" ? item.status = "active" : item.status = "none";
    if (item.status == "active") {
        menuListRef.value = [item];
    }
    else {
        removeComponent(item.id)
    }
};

// 删除组件
const removeComponent = (id: string) => {
    menuListRef.value = menuListRef.value.filter((i) => i.id !== id);
    const item = cimrtsMenuList.value.find((i: any) => i.id === id) as any;
    item.status = "none"
};


// token
const token = ref("");
const cimrtsTokenRef = toVR<string>(d, [cimrtsManager, "cimrtsToken"]);

// 授权
const isAuthRef = toVR<any>(d, [cimrtsManager, "isAuth"]);
// 是不是Cimrts服务
const isCimrtsServiceRef = toVR<string>(d, [cimrtsManager, "isCimrtsService"]);
// cimrtsToken 是否启用
const cimrtsTokenEnableRef = toVR<string>(d, [cimrtsManager, "cimrtsTokenEnable"]);

const isDisabled = computed(() => {
    // 有授权
    if (isAuthRef.value) {
        // 是EarthDS服务
        if (isCimrtsServiceRef.value) {
            // 没开 earthDSToken
            if (!cimrtsTokenEnableRef.value) {
                return false;
            }
            // 开了 earthDSToken
            else {
                // earthDSToken 有值
                if (cimrtsTokenRef.value) {
                    return false;
                }
                // earthDSToken 没值
                else {
                    return true;
                }
            }
        }
        // 不是EarthDS服务
        else {
            return true;
        }
    } else {
        return true;
    }

});

// 点击空白
const whiteSpaceClick = () => {
    console.log("点击空白");

    cimrtsSceneTreeWrapper?.sceneUiTree.clearAllSelectedItems()
    objm.propUiTreeManager.sceneObject = undefined;
}

const currentDialog = ref<undefined | string>(undefined);

// 提交
const submit = () => {
    const c = cimrtsSceneTreeWrapper?.json.root.children
    if (c && c.length > 0) {
        currentDialog.value = "submit"
    } else {
        ElMessage({
            message: "没有待提交的对象",
            type: "warning",
        })
    }
}

// 提交 确定按钮
const submitConfirm = async () => {
    console.log("提交", cimrtsSceneTreeWrapper?.json.root.children);

    await cimrtsManager.submitEditorMultioperation()
    currentDialog.value = undefined
}
d.dispose(cimrtsManager.clearCimrtsWindowEvent.disposableOn(() => {
    menuListRef.value = []
    cimrtsMenuList.value.map((i: any) => i.status = "none")
}))

// 删除所有节点
const deleteAllNode = () => {
    const c = cimrtsSceneTreeWrapper?.json.root.children
    if (c && c.length > 0) {
        currentDialog.value = "deleteAllNode"
    } else {
        ElMessage({
            message: "没有要删除的节点",
            type: "warning",
        })
    }
}
// 删除所有节点 确定按钮
const deleteAllNodeConfirm = () => {
    cimrtsSceneTreeWrapper?.destroyAllSceneObjectTreeItems()
    objm.propSceneTree = undefined
    currentDialog.value = undefined

}


onBeforeUnmount(() => {
    cimrtsMenuList.value.map((i: any) => i.status = "none")
})

</script>

<style scoped>
.box {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    /* padding: 15px; */
    display: flex;
    flex-direction: column;
    gap: 20px;
    align-items: center;
}

.cimrts-scenetree {
    height: 320px;
    width: 100%;
    /* background-color: pink; */
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    border-bottom: 2px solid #EEEEEE;
}

.tree-content {
    width: 100%;
    height: 270px;
}

.submit {
    margin-right: 10px;
    margin-bottom: 10px;
}

.cimrts-info {
    width: calc(100% - 40px);
    height: calc(100% - 380px);

}
</style>